// <T>(value: T | PromiseLike<T>)：Promise<T>

import { rejects } from "assert"
import { promisify } from "util"

// PromiseLike 含有then属性，且then是个函数
function myResolve<T>(tar): Promise<T> {
    if (tar instanceof Promise) return tar
    return new Promise((resolve, reject) => {
        if (tar && tar.then && typeof tar.then === 'function') {
            tar.then(resolve, reject)
        } else {
            resolve(tar)
        }
    })
}
function myReject<T>(tar): Promise<T> {
    return new Promise((resolve, reject) => {
        reject(tar)
    })
}
// Promise中的finally方法，并与调用finally的promise实例，保持与Prmoise一样的状态和接收或拒绝的值或原因
function myFinally(callback) {
    const p = this
    const promise = p.then((val) => {
        callback()
        return val
    }, (reason) => {
        callback()
        throw reason
    })
    return promise
}
// ???
function answerFinally(callback) {
    this.then(value => {
        return Promise.resolve(callback()).then(() => {
            return value
        })
    }, err => {
        return Promise.resolve(callback()).then(() => {
            throw err
        })
    })
}

function myAll(promises) {
    return new Promise((resolve, reject) => {
        let result = []
        let index = 0
        let len = promises.length
        if (len === 0) {
            resolve(result)
            return
        }
        for (let i = 0; i < len; i++) {
            Promise.resolve(promises[i]).then(data => {
                result[i] = data
                index++
                if (index === len) resolve(result)
            }).catch(err => {
                reject(err)
            })
        }
    })
}
interface A {
    status: "pedding"|"fulfilled"|"rejected";
    value?:  unknown;
    reason?: unknown;
}
function allSettled(iterable){
    return new Promise((resolve, reject)=>{
        function addEle

    })
}